/**
 * 
 */
package com.letv.ads.view;

import static com.letv.adlib.sdk.types.AdElement.AdClickShowType.SHOW_EXTERNALWEBBROWSER;
import static com.letv.adlib.sdk.types.AdElement.AdClickShowType.SHOW_INSTALLAPK;
import static com.letv.adlib.sdk.types.AdElement.AdClickShowType.SHOW_INTERNALWEBVIEW;

import java.lang.reflect.Constructor;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.letv.adlib.managers.status.ad.AdStatusManager;
import com.letv.adlib.sdk.types.AdElement.AdMediaType;
import com.letv.adlib.sdk.types.AdElementMime;
import com.letv.ads.AdsManager;
import com.letv.ads.util.AdsUtils;
import com.letv.ads.util.LogInfo;
import com.letv.ads.view.AdView.ClientListener;

/**
 * Created by chengjian 下午9:37:10
 *
 */
public class AdViewGroup extends RelativeLayout implements View.OnClickListener {
    private static final String TAG = "AdViewGroup";
    // 半屏图片是混合广告，广告元素为图片,文字（主标题），文字（副标题）
    private static final Class[] HALF_PIC_ADS = { AdImgaeView.class,
            AdTextView.class, AdTextView.class };
    private ClientListener mClientListener;
    private AdView[] mAdViews;

    /**
     * @param context
     * @param attrs
     */
    public AdViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 显示混合的广告,此类广告包含多个广告元素
     * 
     * @param adInfo
     * @param view
     */
    @SuppressWarnings("unchecked")
    public void showComplexAD(AdElementMime adInfo, AdView... view) {
        if (null != view && view.length <= 0) {
            return;
        }
        mAdViews = view;
        switch (adInfo.mediaFileType) {
        case AdMediaType.HALF_PIC: {
            int length = view.length;
            for (int i = 0; i < length; i++) {
                IAdView childAdView = null;
                AdView adView = null;
                if (view[i] instanceof AdView) {
                    try {
                        adView = view[i];
                        Constructor<?> constructor = HALF_PIC_ADS[i]
                                .getConstructor(Context.class,
                                        AttributeSet.class);
                        childAdView = (IAdView) constructor.newInstance(
                                view[i].getContext(), view[i].getAttributeSet());
                    } catch (Exception exception) {

                    }
                    if (null != childAdView && null != adView) {
                        childAdView.showAD(adInfo);
                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                                LayoutParams.MATCH_PARENT,
                                LayoutParams.MATCH_PARENT);
                        params.gravity = Gravity.CENTER;
                        if (childAdView instanceof View
                                && null == ((View) childAdView).getParent()) {
                            LogInfo.log(TAG, "showComplexAD add view mAdview="
                                    + childAdView);
                            adView.addView((View) childAdView, 0, params);
                        }
                    }
                }

            }
            break;
        }
        default: {
            LogInfo.log(TAG, "showAD default type=" + adInfo.mediaFileType);
            break;
        }

        }
        setTag(adInfo);
        setOnClickListener(this);
    }

    /**
     * 判断点击事件是否被处理
     */
    private boolean handleADClick(AdElementMime adElementMime) {
        if (null != adElementMime) {
            switch (adElementMime.clickShowType) {
            case SHOW_INSTALLAPK: {
                AdsManager.getInstance().downloadAndInstallApk(
                        adElementMime.getClickThrough(), adElementMime.text);
                return true;
            }
            case SHOW_EXTERNALWEBBROWSER:
            case SHOW_INTERNALWEBVIEW: {
                clickGotoWeb(adElementMime);
                return true;
            }
            default: {
                return false;
            }
            }
        }
        return false;
    }

    /**
     * 点击广告跳转到系统浏览器,并请求点击曝光地址和第三方点击曝光地址
     */
    private void clickGotoWeb(AdElementMime adElementMime) {
        String clickThrough = adElementMime.getClickThrough();
        LogInfo.log(TAG, "clickGotoWeb() clickThrough=" + clickThrough);
        if (!TextUtils.isEmpty(clickThrough)) {
            AdsUtils.gotoWeb(getContext(), adElementMime);
        }
    }

    /**
     * 设置广告点击回调
     */
    public void setClientListener(ClientListener listener) {
        this.mClientListener = listener;
        if (null != mAdViews && mAdViews.length > 0) {
            for (int i = 0; i < mAdViews.length; i++) {
                mAdViews[i].setClientListener(listener);
            }
        }

    }

    @Override
    public void onClick(View v) {
        AdElementMime adInfo = null;
        Object object = v.getTag();
        if (object instanceof AdElementMime) {
            adInfo = (AdElementMime) object;
        }
        if (null != adInfo) {
            boolean ishandle = handleADClick(adInfo);
            if (!ishandle) {
                // 如果广告sdk没有处理则交给客户端处理.
                ishandle = mClientListener.handleADClick(adInfo);
            }
            /**
             * 点击统计
             * */
            AdStatusManager statusMgr = new AdStatusManager(adInfo);
            statusMgr.onAdClicked();
        }
    }
}
